#!/usr/bin/env ruby
require 'environment.rb'


def hsize n
  count = 0
  while  n >= 1024 and count < 4
    n /= 1024.0
    count += 1
  end
  format("%.2f",n) + %w(B KB MB GB TB)[count]
end


require 'time'
require 'date'

def backup_lists
  lists = Dir['*.tgz'].map{|n| 
    basename = File.basename(n)
    basename =~ /ZeroPage_([a-z]*)_(.*)\.tgz/
    row = {
      :path=>n, 
      :name=>basename,
      :size=>File.size?(n), 
      :time=>Time.parse(DateTime.strptime($2, '%Y%m%d_%H%M%S%Z').to_s),
      :type=>$1,
      :state=>Dir["#{n}.md5.*"].map{|i| i.sub "#{n}.md5.",""}
    }
    row[:state] << :processing if row[:state].empty?
    row
  }
  lists.sort{|l,r| l[:name] <=> r[:name]}
end

current_path = File.expand_path("")
Dir.chdir '../backup'
lists = backup_lists
Dir.chdir current_path


require 'cgi'
require "erb"
cgi = CGI.new

ext, mime = "html","text/html"
ext, mime ="xml", "text/xml" if /xml/ =~ cgi.query_string
ext, mime ="rss", "application/rss+xml" if /.*\.rss.*/ =~ cgi.query_string
template = File.open("#{File.dirname(__FILE__)}/information.#{ext}.erb").read
cgi.print cgi.header(mime)
cgi.print ERB.new(template).result
